﻿
using ODS.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;


namespace ODS.Utils
{
    

    public class RESTfulService
    {
        #region HTTP Methods

        /// <summary>
        /// 
        /// Get a JSON object using HTTP GET request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>Stream</returns>
        public async static Task<Stream> HTTPGetRequest(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = App.cookieLoginContainer;

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new Exception(Constants.MES_NETWORK_NOT_AVAILABLE);
            }

            HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(Constants.MES_SERVER_ERROR);
            }

            return response.GetResponseStream();

            //Encoding encode = Encoding.GetEncoding("utf-8");

            //Stream stream = response.GetResponseStream();
            //StreamReader streamReader = new StreamReader(stream);

            //return streamReader.ReadToEnd();

        }

        /// <summary>
        /// 
        /// Get a JSON object using HTTP GET request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>Stream</returns>
        public async static Task<Stream> HTTPDeleteRequest(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "DELETE";

            request.CookieContainer = App.cookieLoginContainer;

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new Exception(Constants.MES_NETWORK_NOT_AVAILABLE);
            }

            HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(Constants.MES_SERVER_ERROR);
            }

            return response.GetResponseStream();

            //Encoding encode = Encoding.GetEncoding("utf-8");

            //Stream stream = response.GetResponseStream();
            //StreamReader streamReader = new StreamReader(stream);

            //return streamReader.ReadToEnd();

        }


        /// <summary>
        /// 
        /// Post XML data using HTTP POST request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="postData">XML data to post</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>Stream</returns>
        public async static Task<Stream> HTTPPostRequest(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            //request.ContentType = "application/json;charset=utf-8";
            request.ContentType = String.Format("multipart/form-data; boundary={0}", Constants.kBoundary);

            request.CookieContainer = App.cookieLoginContainer;
 

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new Exception(Constants.MES_NETWORK_NOT_AVAILABLE);
            }

            using (Stream writeStream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
            {
                if (postData != null && postData != string.Empty)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(postData);
                    writeStream.Write(bytes, 0, bytes.Length);
                    
                }
            }

            HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);


            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(Constants.MES_SERVER_ERROR);
            }

            return response.GetResponseStream();

        }

        /// <summary>
        /// 
        /// Post XML data using HTTP POST request
        /// </summary>
        /// <param name="url">Webservice url</param>
        /// <param name="postData">XML data to post</param>
        /// <param name="expectedModel">Model type for JSON to parse to</param>
        /// <returns>Stream</returns>
        public async static Task<Stream> HTTPPutRequest(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            //request.ContentType = "application/json;charset=utf-8";
            request.ContentType = String.Format("multipart/form-data; boundary={0}", Constants.kBoundary);

            request.CookieContainer = App.cookieLoginContainer;

            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                throw new Exception(Constants.MES_NETWORK_NOT_AVAILABLE);
            }

            using (Stream writeStream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
            {
                if (postData != null && postData != string.Empty)
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(postData);
                    writeStream.Write(bytes, 0, bytes.Length);

                }
            }

            HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(Constants.MES_SERVER_ERROR);
            }

            return response.GetResponseStream();

        }

        #endregion

    }
}
